package com.santu.edu.supporter.biz.pay.utils;

import com.santu.edu.supporter.biz.pay.pojo.constants.WxApiConstants;
import com.santu.edu.supporter.biz.pay.pojo.constants.WxPayConstants;
import com.santu.edu.supporter.biz.pay.pojo.dto.WxChatRefundDTO;
import com.santu.edu.supporter.biz.pay.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WxPayRefundUtil {

    /**
     * 封装微信支付申请退款请求参数
     * @param dto 微信支付申请退款请求参数
     * @return 封装后的map微信支付申请退款请求参数对象
     */
    private static Map<String, Object> getRefundParams(WxPayConstants wxPayConstants, WxChatRefundDTO dto) {
        Map<String, Object> paramsMap = new HashMap<>();
        if (StringUtils.isNoneBlank(dto.getTransactionId())) {
            paramsMap.put("transaction_id", dto.getTransactionId());
        } else if (StringUtils.isNoneBlank(dto.getOrderId())) {
            paramsMap.put("out_trade_no", dto.getOrderId());
        } else {
            throw new ServiceException("微信支付订单号和商户订单号必须填写一个");
        }
        paramsMap.put("out_refund_no", dto.getRefundOrderId());
        if (StringUtils.isNoneBlank(dto.getReason())) {
            paramsMap.put("reason", dto.getReason());
        }
        paramsMap.put("notify_url", wxPayConstants.getNotifyDomain().concat(dto.getNotify().getType()));
        Map<String, Object> amountMap = new HashMap<>();
        amountMap.put("refund", dto.getRefundMoney());
        amountMap.put("total", dto.getTotalMoney());
        amountMap.put("currency", "CNY");
        paramsMap.put("amount", amountMap);

        return paramsMap;
    }

    /**
     * 发起微信退款申请
     *
     * @param wxPayConfig 微信配置信息
     * @param param       微信支付申请退款请求参数
     * @param wxPayClient 微信请求客户端（）
     * @return 微信支付二维码地址
     */
    public static String refundPay(WxPayConstants wxPayConfig, WxChatRefundDTO param, CloseableHttpClient wxPayClient) {
        // 1.获取请求参数的Map格式
        Map<String, Object> paramsMap = getRefundParams(wxPayConfig, param);

        // 2.获取请求对象
        HttpPost httpPost = WxPayCommon.getHttpPost(wxPayConfig, WxApiConstants.DOMESTIC_REFUNDS, paramsMap);

        // 3.完成签名并执行请求
        CloseableHttpResponse response = null;
        try {
            response = wxPayClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("微信支付请求失败");
        }

        // 4.解析response对象
        HashMap<String, String> resultMap = WxPayCommon.resolverResponse(response);
        log.info("发起退款参数：{}",resultMap);
        if (resultMap != null) {
            // 返回微信支付退款单号
            return resultMap.get("refund_id");
        }
        return null;
    }

}

